package com.example.service.Impl;

import com.example.Constants.SystemConstants;
import com.example.domain.ResponseResult;
import com.example.domain.vo.IdNameVo;
import com.example.enums.AppHttpCodeEnum;
import com.example.handler.exception.SystemException;
import com.example.mapper.CollegeMapper;
import com.example.mapper.UserMapper;
import com.example.service.CollegeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CollegeServiceImpl implements CollegeService {
    @Resource
    private CollegeMapper collegeMapper;
    @Resource
    private UserMapper userMapper;
    @Override
    public ResponseResult getCollegeList() {
        List<IdNameVo> collegeList = collegeMapper.selectAll();
        HashMap<String, List> stringListHashMap = new HashMap<>();
        stringListHashMap.put("collegeList",collegeList);
        return ResponseResult.okResult(stringListHashMap);
    }

    @Override
    @Transactional
    public ResponseResult addCollege(String name) {
        //检查此学院是否存在
        Integer id = collegeMapper.selectByCollegeName(name);
        if (!ObjectUtils.isEmpty(id)){
            throw  new SystemException(AppHttpCodeEnum.NAME_ERROR);
        }
        collegeMapper.insertCollege(name);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteCollege(Integer id) {
        collegeMapper.deleteCollege(id);
        //将用户college的id为被删除的id覆盖为默认值
        userMapper.updateCollegeByDeleteCollegeId(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult modInitCollege(Integer id) {
        String collegeName = collegeMapper.selectCollegeNameById(id);
        Map<String, String> map = new HashMap<>();
        map.put("name",collegeName);
        return ResponseResult.okResult(map);
    }

    @Override
    @Transactional
    public ResponseResult modCollege(Integer id, String name) {
        //当所编辑的college为默认时，不可以
        if (SystemConstants.DEFAULT_COLLEGE_ID.equals(id)){
            throw new SystemException(AppHttpCodeEnum.DELETE_ADMIN_ERROR);
        }
        //查询当前学院是否存在
        Integer collegeId = collegeMapper.selectByCollegeName(name);
        if (!ObjectUtils.isEmpty(collegeId)){
            throw  new SystemException(AppHttpCodeEnum.NAME_ERROR);
        }
        collegeMapper.updateCollegeById(id,name);
        return ResponseResult.okResult();
    }
}
